package com.lagou.sqlSession;

import com.lagou.anotations.Param;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementid, Object... params) throws Exception {

        //将要去完成对simpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementid);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);

        return (List<E>) list;
    }


    @Override
    public <T> T selectOne(String statementid, Object... params) throws Exception {
        List<Object> objects = selectList(statementid, params);
        if(objects.size()==1){
            return (T) objects.get(0);
        }else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }


    }

    @Override
    public int insert(String statement, Object... params) throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
        return update(statement, params);

    }

    @Override
    public int update(String statement, Object... params) throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
        //将要去完成对simpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statement);
        return simpleExecutor.update(configuration, mappedStatement, params);
    }

    @Override
    public int delete(String statement, Object... parameter) throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
        return update(statement, parameter);
    }


    @Override
    public <T> T getMapper(Class<?> type) {
        // 使用JDK动态代理来为Dao接口生成代理对象，并返回

        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{type}, (proxy, method, args) -> {
            // 底层都还是去执行JDBC代码 //根据不同情况，来调用selctList或者selectOne
            // 准备参数 1：statmentid :sql语句的唯一标识：namespace.id= 接口全限定名.方法名
            // 方法名：findAll
            String methodName = method.getName();
            String className = method.getDeclaringClass().getName();
            // 判断参数上是否有Param注解
            Parameter[] parameters = method.getParameters();
            Map<Object, Object> paramsMap = new HashMap<>();
            for (int i = 0; i < parameters.length; i++) {
                Parameter parameter = parameters[i];
                if (parameter.isAnnotationPresent(Param.class)) {
                    Param annotation = parameter.getAnnotation(Param.class);
                    paramsMap.put(annotation.value(), args[i]);
                }
            }
            String statementId = className+"."+methodName;

            // 准备参数2：params:args
            // 获取被调用方法的返回值类型
            Type genericReturnType = method.getGenericReturnType();
            // 判断是否进行了 泛型类型参数化

            // 获取sql类型
            MappedStatement mappedStatement = this.configuration.getMappedStatementMap().get(statementId);
            String sqlCommandType = mappedStatement.getSqlCommandType();
            switch (sqlCommandType) {
                case "select":
                    return select(args, paramsMap, statementId, genericReturnType);
                case "insert":
                    return doInsert(args, statementId, paramsMap);
                case "update":
                     return doUpdate(args, paramsMap, statementId);
                case "delete":
                    return doDelete(args, statementId, paramsMap);
                default:
                    return null;
            }

        });

        return (T) proxyInstance;
    }

    private Object doDelete(Object[] args, String statementId, Map<Object, Object> paramsMap) throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
        if (paramsMap.isEmpty()) {
            return delete(statementId, args);
        } else {
            return delete(statementId, paramsMap);
        }
    }

    private Object doInsert(Object[] args, String statementId, Map<Object, Object> paramsMap) throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
        if (paramsMap.isEmpty()) {
            return insert(statementId, args);
        } else {
            return insert(statementId, paramsMap);
        }
    }

    private Object doUpdate(Object[] args, Map<Object, Object> paramsMap, String statementId) throws SQLException, NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
        if (paramsMap.isEmpty()) {
            return update(statementId, args);
        } else {
            return update(statementId, paramsMap);
        }
    }

    private Object select(Object[] args, Map<Object, Object> paramsMap, String statementId, Type genericReturnType) throws Exception {
        if(genericReturnType instanceof ParameterizedType) {
            if (paramsMap.isEmpty()) {
                return selectList(statementId, args);
            } else {
                return selectList(statementId, paramsMap);
            }

        } else {
            if (paramsMap.isEmpty()) {
                return selectOne(statementId, args);
            } else {
                return selectOne(statementId, paramsMap);
            }
        }
    }


}
